#include "usermanager.h"
#include "databasemanager.h"
#include <QCryptographicHash>
#include <QRandomGenerator>

static QAtomicPointer<UserManager> instance = nullptr;
static QMutex instanceMutex;

UserManager::UserManager(QObject *parent) : QObject(parent), databaseManager(nullptr) {}

void UserManager::setDatabaseManager(DatabaseManager* manager) {
    databaseManager = manager;
}

QString UserManager::hashPassword(const QString &password, const QString &) const {
    // 确保直接对密码明文进行单次SHA-256哈希
    QByteArray data = password.toUtf8();
    return QCryptographicHash::hash(data, QCryptographicHash::Sha256).toHex();
}


std::pair<bool, UserManager::UserError> UserManager::validateLogin(
    const QString &username, const QString &password)
{
    QString safeUsername = username;
    safeUsername.replace("'", "''");

    QString query = QString("AUTH:SELECT password FROM users WHERE username='%1'")
                   .arg(safeUsername);

    QString response = executeQuery(query);
    qDebug() << "Auth response:" << response; // 调试输出

    if (response.startsWith("AUTH_ERROR:")) {
        if (response.contains("USER_NOT_FOUND")) {
            return {false, UserError::UserNotFound};
        }
        return {false, UserError::ConnectionError}; // 其他错误归类为连接问题
    }

    if (!response.startsWith("AUTH_SUCCESS:")) {
        qDebug() << "Unexpected response format:" << response;
        return {false, UserError::ConnectionError};
    }

    QString storedHash = response.mid(13); // 去掉 "AUTH_SUCCESS:"
    QString inputHash = hashPassword(password, "");

    qDebug() << "Input password:" << password; // 打印原始密码
    qDebug() << "Client hash:" << inputHash;
    qDebug() << "Server hash:" << storedHash; // 从服务端返回的哈希

    if (inputHash != storedHash) {
        qDebug() << "Hash mismatch! Check password or hash algorithm.";
    }

    return {inputHash == storedHash,
            inputHash == storedHash ? UserError::Success : UserError::WrongCredentials};
}

QString UserManager::executeQuery(const QString &query) {
    QMutexLocker locker(&m_mutex);
    if (!databaseManager) {
        databaseManager = DatabaseManager::instance(); // 确保兜底逻辑
        if (!databaseManager) {
            return "Error: No DB Manager (Fallback failed)";
        }
    }
    return databaseManager->sendRequest(query);
}

QString UserManager::executeUserQuery(const QString &query)
{
    auto db = DatabaseManager::instance();
    QString result = db->sendRequest(query);

    if(result.startsWith("Error:")) {
        qWarning() << "Query failed:" << result;
    }
    return result;
}

std::pair<bool, UserManager::UserError> UserManager::registerUser(const QString &username,
                                                                const QString &password,
                                                                const QString &email,
                                                                const QString &phone,
                                                                const QString &role,
                                                                const QString &nickname)
{
    if (username.isEmpty() || password.isEmpty() || email.isEmpty() || phone.isEmpty()) {
        return {false, UserError::InvalidInput};
    }

    QMutexLocker locker(&m_mutex);

    // 检查用户名是否已存在
    QString checkQuery = QString("SELECT username FROM users WHERE username = '%1'").arg(username);
    QString checkResult = executeUserQuery(checkQuery);

    if (!checkResult.isEmpty() && !checkResult.startsWith("Error:") && checkResult != "No results found") {
        return {false, UserError::UserExists};
    }

    QString passwordHash = hashPassword(password, "");

    // 插入新用户（不包含salt列）
    QString insertQuery = QString(
        "INSERT INTO users (username, password, email, phone, role, nickname) "
        "VALUES ('%1', '%2', '%3', '%4', '%5', '%6')")
        .arg(username)
        .arg(passwordHash)
        .arg(email)
        .arg(phone)
        .arg(role)
        .arg(nickname);

    QString insertResult = executeUserQuery(insertQuery);

    if (insertResult.startsWith("Error:")) {
        qDebug() << "注册失败:" << insertResult;
        return {false, UserError::QueryFailed};
    }

    return {true, UserError::Success};
}

std::pair<bool, UserManager::UserError> UserManager::resetPassword(const QString &username,
                                                                 const QString &input,
                                                                 const QString &newPassword)
{

    QMutexLocker locker(&m_mutex);

    // 验证用户身份
    QString verifyQuery = QString(
        "SELECT id FROM users WHERE username = '%1' AND (email = '%2' OR phone = '%2')")
        .arg(username)
        .arg(input);

    QString verifyResult = executeUserQuery(verifyQuery);

    if (verifyResult.isEmpty() || verifyResult.startsWith("Error:")) {
        return {false, UserError::QueryFailed};
    }

    if (verifyResult == "No results found") {
        return {false, UserError::UserNotFound};
    }

    // 使用固定 salt（因为数据库没有salt列）
    const QString FIXED_SALT = "FixedSaltForSecurity123!";
    QString newPasswordHash = hashPassword(newPassword, "");

    // 更新密码（不更新salt列）
    QString updateQuery = QString(
        "UPDATE users SET password = '%1' WHERE username = '%2'")
        .arg(newPasswordHash)
        .arg(username);

    QString updateResult = executeUserQuery(updateQuery);

    if (updateResult.startsWith("Error:")) {
        qDebug() << "密码重置失败:" << updateResult;
        return {false, UserError::QueryFailed};
    }

    return {true, UserError::Success};
}

QString UserManager::getUserRole(const QString &username) {
    QString query = QString("SELECT role FROM users WHERE username='%1'").arg(username);
    QString result = executeQuery(query).trimmed();  // 确保去除换行符
    qDebug() << "Raw role query result:" << result;

    // 处理可能的 "admin |" 格式
    if (result.contains('|')) {
        return result.split('|').first().trimmed();
    }
    return result;
}

void UserManager::setCurrentUser(const QString &username, const QString &role)
{
    QMutexLocker locker(&m_mutex);
    m_currentUsername = username;
    m_currentRole = role;
}

QString UserManager::getCurrentUsername() const
{
    QMutexLocker locker(&m_mutex);
    return m_currentUsername;
}


void UserManager::setCurrentUserRole(const QString &role) {
    QMutexLocker lock(&m_mutex);
    m_currentRole = role.trimmed();
    qDebug() << "[UserManager] Role SET:" << m_currentRole;
}


QString UserManager::getCurrentUserRole() const {
    QMutexLocker lock(&m_mutex);
    qDebug() << "[UserManager] Returning role:" << m_currentRole;
    return m_currentRole;
}
